<?php

namespace app\api\model;

use think\Model;
use think\exception\ValidateException;

class MallDealLog extends Model
{

    protected $name = "mall_deal_log";

    protected $table = "";

    protected $deleteTime = "delete_time";

    public array $notes = [
      'deal_type' => 
      [
        1 => '闪送',
        2 => '达达',
        3 => '蜂鸟',
      ],
    ];

    /**
     * 新增
     */
    public function dealLogCreate($param)
    {

        // 验证数据
        try {
            validate([
                'appid'  => 'require', 
                'deal_type'  => 'require', 
                'order_id'  => 'require', 
                'sys_number'  => 'require', 
                'deal_money'  => 'require', 
            ])->message([
                'appid.require'  => 'appid必须传递',   
                'deal_type.require'  => 'deal_type必须传递',   
                'order_id.require'  => 'order_id必须传递',   
                'sys_number.require'  => 'sys_number必须传递',   
                'deal_money.require'  => 'deal_money必须传递',   
            ])->check($param);
        } catch (ValidateException $e) {
            return result_error($e->getError());
        }
        
        $data['appid'] = $param['appid'] ?? '';//appid
        $data['deal_type'] = $param['deal_type'] ?? '';//交易类型 {radio} (1:闪送, 2:达达,3:蜂鸟,-1充值)
        $data['order_id'] =$param['order_id'];//order_id
        $data['sys_number'] = $param['sys_number'] ?? '';//系统单号
        $data['deal_money'] = $param['deal_money'] ?? 0;//交易金额，单位：分
        $data['deal_type_str'] = $param['deal_type_str'] ?? '';//交易类型说明
        $data['remark'] = $param['remark'] ?? 0;//备注

        $find = $this->where('appid',$data['appid'])->order('id desc')->find();
        $data['deal_balance'] =$find['deal_balance']-$data['deal_money'];//余额，单位：分
        if($data['deal_balance'] < 0){
            return result_error('余额不足');
        }
          
            
        // 创建
        try {
            $result = $this->save($data);

            if ($result) {
                return result_success('success', $data);
            } else {
                return result_error('保存失败');
            }
        } catch (\Exception $e) {
            return result_error($e->getMessage());
        }
    }


}